<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useUserStore } from "@/stores/user";
import { useRouter } from 'vue-router';
import { getChatList, getHistoryMessage } from '@/api/Chat.js';

const router = useRouter();
const userStore = useUserStore();

// Chat data
const chatList = ref([]);
const currentConversation = ref(null);
const messageList = ref([]);
const websocket = ref(null);
const newMessage = ref(''); // 用于发送的消息输入框的内容

// WebSocket 连接的建立
const setupWebSocket = () => {
  const wsUrl = `ws://localhost:8080/imserver/${userStore.UserId}`;
  websocket.value = new WebSocket(wsUrl);

  websocket.value.onmessage = (event) => {
    const receivedMessage = JSON.parse(event.data);
    handleIncomingMessage(receivedMessage);
  };

  websocket.value.onclose = () => {
    console.log('WebSocket connection closed');
  };
};

// 处理接收到的消息
const handleIncomingMessage = (message) => {
  // 打印接收到的消息，方便调试
  console.log('Received message:', message);

  // 判断接收到的消息是否属于当前会话
  if (currentConversation.value && currentConversation.value.conversationId === parseInt(message.conversationId)) {
    // 如果属于当前会话，将该消息添加到 messageList 中
    const newMessage = {
      messageId: Date.now(),  // 用于生成一个临时的唯一ID
      conversationId: message.conversationId,
      senderId: message.from,
      receiverId: userStore.UserId,
      text: message.text
    };
    messageList.value = [...messageList.value, newMessage];
  } else {
    // 如果消息不是当前会话的，可以提示用户有新消息
    console.log('收到新消息，但不是当前会话:', message);
  }
};

// 发送消息
const sendMessage = () => {
  if (newMessage.value.trim() === '' || !currentConversation.value) return;

  const messageData = {
    from: userStore.UserId,
    to: currentConversation.value.user1Id === userStore.UserId
        ? currentConversation.value.user2Id
        : currentConversation.value.user1Id,
    text: newMessage.value,
    conversationId: currentConversation.value.conversationId
  };

  if (websocket.value && websocket.value.readyState === WebSocket.OPEN) {
    websocket.value.send(JSON.stringify(messageData));
    // 将消息推送到消息列表中（展示用户自己发送的消息）
    const localMessage = {
      messageId: Date.now(),  // 用于生成一个临时的唯一ID
      conversationId: messageData.conversationId,
      senderId: userStore.UserId,
      receiverId: messageData.to,
      text: messageData.text
    };
    messageList.value = [...messageList.value, localMessage];
    newMessage.value = ''; // 发送后清空输入框
  }
};

// Fetch chat list
const fetchChatList = async () => {
  const response = await getChatList(userStore.UserId);
  chatList.value = response.data.data;
};

// Fetch history messages for selected conversation
const fetchHistoryMessages = async (conversationId) => {
  const response = await getHistoryMessage(conversationId);
  messageList.value = response.data.data;
};

// Handle conversation click
const selectConversation = (conversation) => {
  currentConversation.value = conversation;
  fetchHistoryMessages(conversation.conversationId);
};

// Get the other user's info in the chat
const getOtherUser = (conversation) => {
  if (conversation.user1Id === userStore.UserId) {
    return {
      name: conversation.user2Name,
      avatar: conversation.user2Avatar
    }
  } else {
    return {
      name: conversation.user1Name,
      avatar: conversation.user1Avatar
    }
  }
};

// Get message alignment based on sender
const isUserMessage = (message) => {
  return message.senderId === userStore.UserId;
};

// Lifecycle hooks
onMounted(() => {
  fetchChatList();
  setupWebSocket();
});

onUnmounted(() => {
  if (websocket.value) {
    websocket.value.close();
  }
});
</script>

<template>
  <div class="chat-container">
    <!-- Chat List on the left -->
    <div class="chat-list">
      <ul>
        <li v-for="conversation in chatList" :key="conversation.conversationId"
            @click="selectConversation(conversation)"
            :class="['conversation-item', currentConversation && currentConversation.conversationId === conversation.conversationId ? 'selected' : '']">
          <div class="user-info">
            <img :src="getOtherUser(conversation).avatar || 'default-avatar.png'" alt="Avatar" class="avatar">
            <span>{{ getOtherUser(conversation).name }}</span>
          </div>
        </li>
      </ul>
    </div>

    <!-- Chatbox on the right -->
    <div class="chat-box" v-if="currentConversation">
      <div class="message-list">
        <div v-for="(message, index) in messageList" :key="index"
             :class="['message-item', isUserMessage(message) ? 'message-right' : 'message-left']">
          <!-- Display the avatar -->
          <img v-if="!isUserMessage(message)" :src="getOtherUser(currentConversation).avatar || 'default-avatar.png'"
               alt="Avatar" class="message-avatar">
          <img v-if="isUserMessage(message)" :src="userStore.avatar || 'default-avatar.png'" alt="Avatar"
               class="message-avatar">
          <!-- Display the message content -->
          <span class="message-content">{{ message.text }}</span>
        </div>
      </div>

      <!-- Message input and send button -->
      <div class="message-input">
        <input type="text" v-model="newMessage" placeholder="Type your message here..." @keyup.enter="sendMessage" />
        <button @click="sendMessage">Send</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  display: flex;
  gap: 10px;
  height: 80vh;
  padding: 10px;
  width: 70%;
  margin-left: 10%;
}

.chat-list {
  width: 250px;
  border-right: 1px solid #ccc;
  padding: 10px;
  background-color: #f9f9f9;
  overflow-y: auto;
}

.chat-box {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.message-list {
  padding: 10px;
  flex-grow: 1;
  overflow-y: auto;
}

.message-item {
  display: flex;
  align-items: center;
  margin: 10px 0;
  max-width: 70%;
  word-wrap: break-word;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.message-content {
  padding: 8px 12px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.4;
  background-color: #f1f1f1;
}

.message-left .message-content {
  background-color: #f1f1f1;
}

.message-right {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message-right .message-avatar {
  margin-left: 10px;
  margin-right: 0;
}

.message-right .message-content {
  background-color: #b3e5fc;
}

.conversation-item {
  padding: 10px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.conversation-item:hover {
  background-color: #f0f0f0;
}

.selected {
  background-color: #d0d0d0; /* Darker color for selected conversation */
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.user-info {

  display: flex;
  align-items: center;
  gap: 10px;
}

.message-input {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.message-input input {
  flex-grow: 1;
  padding: 10px;
  border-radius: 20px;
  border: 1px solid #ccc;
}

.message-input button {
  padding: 10px 20px;
  border-radius: 20px;
  background-color: #4caf50;
  color: white;
  border: none;
  cursor: pointer;
}

.message-input button:hover {
  background-color: #45a049;
}
</style>
